#!/usr/bin/env python

import wx

class Image(wx.Window):
    '''Image class
    
    @author Julot <andy.julot@gmail.com>
    @since Thursday, August 4, 2011. 03:14:51 PM'''
    
    _image = None
    _blank = None
    
    def __init__(self, parent):
        wx.Window.__init__(self, parent, style=wx.BORDER_THEME)
        
        self.bitmap = wx.StaticBitmap(self)
        self.Bind(wx.EVT_SIZE, self._onSize)
        self._blank = wx.EmptyBitmap(1 , 1)
    
    @property
    def image(self):
        return self._image
    
    @image.setter
    def image(self, value):
        self._image = value
        self._draw()
    
    def _onSize(self, event):
        event.Skip()
        if self._image: self._draw()
    
    def _draw(self):
        '''Draw bitmap
        
        @return boolean whether drawing operation succeeds'''
        
        image = self._image
        if image:
            width, height = image.GetSize()
            if height > self.Size.height or width > self.Size.width:
                # Image needs resizing to fit the parent.
                # Use height as anchor.
                width, height = self.Size
                width = (height * image.Width) / image.Height
                if width > self.Size.width:
                    width, height = self.Size
                    # Width is still wider than the container, switch to width
                    # as anchor.
                    height = (width * image.Height) / image.Width
            image = image.ResampleBicubic(width, height)
            x = (self.Size.width - width) / 2
            y = (self.Size.height - height) / 2
            coord = wx.Point(x, y)
            self.bitmap.SetPosition(coord)
            self.bitmap.SetBitmap(image.ConvertToBitmap())
            self.Refresh()
        else:
            self.clear()
    
    def clear(self):
        self._image = None
        self.bitmap.SetBitmap(self._blank)
